//
//  HomePageVC.swift
//  首页
//
//  Created by 千策万划-mini on 2025/4/28.
//

import Foundation
import FBSDKCoreKit

class HomePageVC: BaseVC {
    
    private var modelHome: ModelHome = ModelHome()
    
    // MARK: - lazy
    lazy var loginView: LoginView = {
        let result = LoginView()
        return result
    }()
    lazy var bigCardVC: HomePageBigCardVC = {
        let result = HomePageBigCardVC()
        result.blockRefreshHome = { [weak self] in
            guard let self = self else { return }
            self.requestAppHome()
        }
        result.viewContent.blockFeedbackSuccess = { [weak self] in
            guard let self = self else { return }
            UIView.animate(withDuration: 0.6) {
                self.bigCardVC.viewContent.imageFeedback.alpha = 0
            } completion: { _ in
                UIView.animate(withDuration: 0.6) {
                    self.bigCardVC.viewContent.resetView(self.modelHome)
                    self.bigCardVC.tableView.tableHeaderView = self.bigCardVC.viewContent
                }
            }
        }
        result.viewContent.blockApplyNow = { [weak self] in
            guard let self = self else { return }
            if isForceLocationAndNotOpen() == false {
                self.requestApply()
            }
        }
        result.viewContent.blockNoLogin = { [weak self] in
            guard let self = self else { return }
            loginView.show()
        }
        return result
    }()
    lazy var smallCardVC: HomePageSmallCardVC = {
        let result = HomePageSmallCardVC()
        result.view.isHidden = true;
        result.blockRefreshHome = { [weak self] in
            guard let self = self else { return }
            self.requestAppHome()
        }
        result.viewContent.blockApplyClick = { [weak self] in
            guard let self = self else { return }
            if isForceLocationAndNotOpen() == false {
                self.requestApply()
            }
        }
        // 逾期提醒
        result.viewContent.blockOverdueRemindClick = { [weak self] (tag) in
            guard let self = self else { return }
            if isForceLocationAndNotOpen() == false {
                let vc = BaseWebVC()
                vc.webUrl = self.modelHome.farmyard.impulsive[tag].quiet
                GB_Nav?.pushViewController(vc, animated: true)
            }
        }
        // 产品列表 - 产品申请
        result.blockApplyClick = { [weak self](code) in
            guard let self = self else { return }
            if isForceLocationAndNotOpen() == false {
                self.requestApply(productCode: code)
            }
        }
        return result
    }()
    lazy var locationAlertView: PermissionsAlertView = {
        let result = PermissionsAlertView()
        result.resetView(model: ModelBtn(title: "Permissions", content: DESC_LOCATION, leftTitle: "Stop", rightTitle: "Turning On"))
        return result
    }()
    
    // MARK: - viewDidLoad
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestAppHome()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
            // 延时 1 秒 上报googleMarket接口
            self?.requestGoogleMarket()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(reloadHomeInfo), name: Notification.Name(NOTICE_LOGIN_SUCCESS), object: nil)
        configUI()
    }
    
    // 通知事件
    @objc private func reloadHomeInfo() {
        requestAppHome()
    }
    
    func configUI() {
        viewBg.image = UIImage(named: "icon_home_bg")
        viewBg.widthHeight = XY(SCREEN_WIDTH, SCREEN_WIDTH/1125*3801)
        viewBg.leftTop = XY(0, 0)
        setUpChildVC()
    }
    
    func setUpChildVC() {
        addChild(bigCardVC)
        addChild(smallCardVC)
        
        // 大卡位
        bigCardVC.view.frame = CGRectMake(0, STATUSBAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-STATUSBAR_HEIGHT-80);
        bigCardVC.tableView.frame = bigCardVC.view.bounds
        view.addSubview(bigCardVC.view)
        
        // 小卡位
        smallCardVC.view.frame = bigCardVC.view.frame
        smallCardVC.tableView.frame = smallCardVC.view.bounds
        view.addSubview(smallCardVC.view)
    }
    
    // MARK: - request
    func isForceLocationAndNotOpen() -> Bool {
        // 强制定位开启-并且未开启定位，不允许点击
        if (GlobalMethod.readBoolFromUserDefaults(forKey: LOCAL_FORCE_LOCATION) && !GlobalMethod.isOnLocationAuthorization()) {
            locationAlertView.show()
            return true
        }else{
            return false
        }
    }
    
    
    // 首页信息
    func requestAppHome() {
        HomeRequestApi.home { request, responseData in
            guard let res = responseData as? [String: Any] else {return}
            if let model = ModelHome.deserialize(from: res) {
                self.modelHome = model
                // 1 = 强制登录
                GlobalMethod.writeBool(self.modelHome.peeked == 1, forKey: LOCAL_FORCE_LOCATION)
                // 判断显示大/小卡位
                if (self.modelHome.serves?.wisest == "respects") {
                    // 大卡位
                    self.bigCardVC.viewContent.resetView(self.modelHome)
                    self.bigCardVC.view.isHidden = false
                    self.smallCardVC.view.isHidden = true
                }else{
                    // 小卡位
                    self.smallCardVC.viewContent.resetView(self.modelHome)
                    self.smallCardVC.modelDetail = self.modelHome
                    self.smallCardVC.tableView.reloadData()
                    self.bigCardVC.view.isHidden = true
                    self.smallCardVC.view.isHidden = false
                }
            }
        } failure: { request, error in
            
        }
    }
    
    // 申请
    func requestApply(productCode: String = "") {
        // 登录状态，并且有定位权限以后，每次点击首页点击大卡位、小卡位、产品列表的时候都上报 位置信息、设备信息
        GlobalMethod.asyncBlock {
            self.uploadDeviceInfo()
            self.uploadLocationInfo()
        }
        
        let code = isStr(productCode) ? productCode : UnPackStr(self.modelHome.serves?.impulsive.first?.gnawed)
        HomeRequestApi.productApply(productCode: code) { request, responseData in
            guard let res = responseData as? [String: Any] else {return}
            if let model = ModelProductApply.deserialize(from: res) {
                if model.quiet.contains("http") {
                    // http：跳转web
                    let vc = BaseWebVC()
                    vc.webUrl = model.quiet
                    GB_Nav?.pushViewController(vc, animated: true)
                }
                else{
                    if model.quiet.contains(LOCAL_PRODUCT_DETAIL_ROUTE) {
                        // 产品详情 "quiet": "would://gasped.Hound.nothing/ashNinjaYam?carry=2"
                        if let quietRange = model.quiet.range(of: "?", options: .backwards) {
                            let quietPart = model.quiet[quietRange.upperBound...]
                            let pairs = quietPart.components(separatedBy: "&")
                            for pair in pairs {
                                let components = pair.components(separatedBy: "=")
                                if components.first == "carry" && components.count > 1 {
                                    let makeValue = components.last?.trimmingCharacters(in: .whitespaces) ?? ""
                                    let vc = ProductDetailVC()
                                    vc.productCode = makeValue
                                    GB_Nav?.pushViewController(vc, animated: true)
                                    break
                                }
                            }
                        }
                    }
                }
            }
        } failure: { request, error in
            
        }
    }
    
    // 上报 设备信息
    func uploadDeviceInfo() {
        HomeRequestApi.uploadDeviceInfo { request, responseData in
            
        } failure: { request, error in
            
        }
    }
    
    // 上报 位置信息
    func uploadLocationInfo() {
        LocationService.shared.startUploca {
            HomeRequestApi.uploadLocationInfo { request, responseData in
                
            } failure: { request, error in
                
            }
        }
    }
    
    // Google Market上报 - 获取 faceBook 配置
    func requestGoogleMarket() {
        if GlobalMethod.readBoolFromUserDefaults(forKey: LOCAL_HOME_GOOGLE_MARKET, isPrefixed: false) == false {
            GlobalMethod.writeBool(true, forKey: LOCAL_HOME_GOOGLE_MARKET, isPrefixed: false)
            HomeRequestApi.getFaceBookConfig { request, responseData in
                guard let res = responseData as? [String: Any] else {return}
                if let model = ModelFaceBook.deserialize(from: res) {
                    Settings.shared.appID = model.insideasedfqw.doors
                    Settings.shared.clientToken = model.insideasedfqw.scolded
                    Settings.shared.displayName = model.insideasedfqw.scolds
                    Settings.shared.appURLSchemeSuffix = model.insideasedfqw.ledge
                    ApplicationDelegate.shared.application(UIApplication.shared,didFinishLaunchingWithOptions: nil)
                }
            } failure: { request, error in
                
            }
        }
    }
}
